//
// Created by 崔世强 on 2018/4/2.
// Copyright (c) 2018 Facebook. All rights reserved.
//

import Foundation
import SwiftyJSON

class ModifyGroupNickNameHandler: NoticeHandlerProtocol {

    static let instance = ModifyGroupNickNameHandler()

    private init() {
    }

    func handler(_ msg: Message) {
        do {
            let db = SQLiteHelper.getDb()
            let json = JSON(parseJSON: msg.content ?? "")
            try db.run(transaction: { _ in
                if let groupMember = try GroupDao.getMember(msg.sessionServerId, userId: msg.userId) {
                    try GroupDao.updateMemberNickName(msg.sessionServerId, userId: msg.userId, nickName: json["nickName"].stringValue)
                }
            })
        } catch {
            print(error)
        }
    }

    func show(_ msg: ChatMessage) -> String? {
        do {
            let contact = try ContactDao.getContact(msg.from)
            let groupMember = try GroupDao.getMember(msg.sessionId, userId: msg.from)

            let json = JSON(parseJSON: msg.text ?? "")

            var name = contact?.remarkName ?? groupMember?.nickName ?? contact?.name
            if msg.isMe {
                name = "你"
            }
            return "\(name ?? "管理员" )修改群昵称为\(json["nickName"].stringValue)"

        } catch {
            return msg.text
        }
    }
}
